//
//  KLSettingViewController.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "GCMineInfoViewController.h"
#import "STPhotoUrlImageBrowerController.h"
#import "STTextView.h"
#import "GCQrCodeViewController.h"
#define MAX_NUM 100
@interface GCMineInfoViewController ()<STPhotoUrlImageBrowerControllerDelegate,STActionSheetDelegate>
@property(nonatomic, strong) NSArray  <STTableEasyModel*>                   *dataSouce;
@property(nonatomic, strong) STButton                     *iconButton;
@property(nonatomic, strong) STPhotoUrlImageBrowerController                     *pickerVC;
@property(nonatomic, strong) STUrlPhotoModel                     *imageModel;
@property(nonatomic, strong) STTextView                     *textView;
@property(nonatomic, strong) STLabel                     *numLable;

@end

@implementation GCMineInfoViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    [self configSubView];
    [self configTableFooter];
    [self addNotifacations];
    [self reloadData];
    [self.tableView st_autoAdjustAllResponder];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.userModel) {
        //  [self sendMyInfoRequest];
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(UITextFieldTextDidChange:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(UITextViewTextDidChange:)
                                                 name:UITextViewTextDidChangeNotification
                                               object:nil];
}
- (void)UITextViewTextDidChange:(NSNotification*)notify{
    if (notify.object == self.textView) {
        UITextView *textView = (UITextView *)notify.object;
        NSString *toBeString = textView.text;
        NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage; // 键盘输入模式
        if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，五笔，简体手写
            UITextRange *selectedRange = [textView markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position) {
                if (toBeString.length > MAX_NUM) {
                    textView.text = [toBeString substringToIndex:MAX_NUM];
                }
                NSInteger num = self.textView.text.length;
                self.numLable.text = [NSString stringWithFormat:@"%ld/200", num];
            }
            // 有高亮选择的字符串，则暂不对文字进行统计和限制
            else{
                
            }
        }
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        else{
            NSInteger num = toBeString.length;
            self.numLable.text = [NSString stringWithFormat:@"%ld/200",num];
            if (toBeString.length >= MAX_NUM) {
                textView.text = [toBeString substringToIndex:MAX_NUM];
            }
        }
    }
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                title:nil
                                           titleColor:nil
                                            titleFont:0
                                         cornerRadius:20
                                      backgroundColor:nil
                                      backgroundImage:[UIImage imageNamed:@"liao"]
                                                image:[UIImage imageNamed:@"liao"]];
    [self.iconButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedIconCell];
    }];
    
    // [self configTableFooter];
}
- (void)configTableFooter{
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = [UIColor whiteColor];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 0, UIScreenWidth - 20, 50)
                                                     text:@"个人介绍"
                                                textColor:SecendTextColor
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [footer addSubview:titleLable];
    
    
    self.textView = [[STTextView alloc] initWithFrame:CGRectMake(16, titleLable.bottom, UIScreenWidth - 32, 144)];
    self.textView.placeholder = @"请输入文字内容";
    self.textView.placeholderColor = SecendTextColor;
    self.textView.backgroundColor = TM_backgroundColor;
    [footer addSubview:self.textView];
    
    self.numLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)
                                              text:@"0/200"
                                         textColor:SecendTextColor
                                              font:12
                                       isSizetoFit:NO
                                     textAlignment:NSTextAlignmentRight];
    self.numLable.st_right = self.textView.width - 16;
    self.numLable.bottom = self.textView.bottom - 5;
    [footer addSubview:self.numLable];
    
    footer.height = self.textView.bottom + 40;
    self.tableView.tableFooterView = footer;
}
- (void)reloadData{
    
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    STTableEasyModel * versionModel = [[STTableEasyModel alloc] initWithTextString:@"当前版本"
                                                                      detailString:[NSString stringWithFormat:@"v%@",version]];
    versionModel.accessoryType = UITableViewCellAccessoryNone;
    [self.iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"1"]];
    NSString * nickName = @"大佬";
    NSArray * sectionOne = @[
                             [[STTableEasyModel alloc] initWithTextString:@"头像" accessoryView:self.iconButton],
                             [[STTableEasyModel alloc] initWithTextString:@"昵称" detailString:nickName],
                             [[STTableEasyModel alloc] initWithTextString:@"性别" detailString:@"男"],
                             [[STTableEasyModel alloc] initWithTextString:@"地址" detailString:@"成都"],
                             [[STTableEasyModel alloc] initWithTextString:@"用户ID" detailString:@"123"],
//                             [[STTableEasyModel alloc] initWithTextString:@"出生日期" detailString:nickName],
                             [[STTableEasyModel alloc] initWithTextString:@"二维码" detailString:@""]];
    
    
    self.dataSouce = sectionOne;
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 24;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.textLabel.text = model.textString;
    cell.detailTextLabel.text = model.detailString;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        if ([model.textString containsString:@"用户"]) {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }else{
           cell.accessoryType = model.accessoryType;
        }
       
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if ([model.textString isEqualToString:@"头像"]) {
        [self onSelectedIconCell];
    }
    if ([model.textString isEqualToString:@"昵称"]) {
        [self onSelectedNickNameCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"性别"]) {
        [self onSelctedGenderCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"地址"]) {
        [self onSelctedAreaCellWithIndexPath:indexPath model:model];
    }
    if ([model.textString isEqualToString:@"二维码"]) {
        [self.navigationController pushViewController:[GCQrCodeViewController new] animated:YES];
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSelectedIconCell{
    STUrlPhotoModel * model = [STUrlPhotoModel new];
    model.thumbImage = self.iconButton.currentImage;
    if (self.userModel) {
        model.thumbImageUrl = @"";
    }
    self.imageModel = model;
    self.pickerVC = [[STPhotoUrlImageBrowerController alloc] initWithArray:@[model] curentIndex:0];
    self.pickerVC.STPhotoUrlImageBrowerControllerdelegate = self;
    self.pickerVC.themeColor = FirstTextColor;
    self.pickerVC.shouldHideBottomView = YES;
    [self presentViewController:self.pickerVC animated:NO completion:nil];
}
- (void)onSelectedNickNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              model.detailString = text;
                                                              [self.tableView reloadData];
                                                              //                                                              [self sendChangeNickNameRequest:text withModel:model];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)onSelctedRealNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              model.detailString = text;
                                                              [self.tableView reloadData];
                                                              //                                                              [self sendChangeNickNameRequest:text withModel:model];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)onSelctedGenderCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSArray * array = @[@"男",@"女"];
    [self showActionSheet:array andWithBlock:^(int tag) {
        model.detailString = array[tag];
        [self.tableView reloadData];
    }];
}
- (void)onSelctedDateCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    STPickerViewController * pickerVC = [[STPickerViewController alloc] initWithDefualtDatePickerWithHandle:^(NSDate *date) {
        model.detailString = date.st_yyyyMMddByLineWithDate;
        [self.tableView reloadData];
    }];
    [self presentViewController:pickerVC animated:NO completion:nil];
}
- (void)onSelctedWorkCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSArray * array = @[@"ios",@"Android",@"php",@"java"];
    STPickerViewController * pickerVC = [[STPickerViewController alloc] initWithPickerArray:@[array] andWithHandle:^(NSArray<NSString *> *stringArray) {
        model.detailString = stringArray.lastObject;
        [self.tableView reloadData];
    }];
    [self presentViewController:pickerVC animated:NO completion:nil];
}
- (void)onSelctedAreaCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    STPickerViewController * pickerVC = [[STPickerViewController alloc]initWithDefualtAreaPickerWithHandle:^(NSString *finshString, NSString *area, NSString *city, NSString *provence) {
        model.detailString = [NSString stringWithFormat:@"%@%@",provence,city];
        [self.tableView reloadData];
    }];
    [self presentViewController:pickerVC animated:NO completion:nil];
}
#pragma mark --STPhotoUrlImageBrowerControllerDelegate
- (UIView*)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STUrlPhotoModel*)model{
    return self.iconButton;
}
- (void)rightBarActionFromController:(STPhotoUrlImageBrowerController*)controller currentIndexPath:(NSIndexPath *)curentIndexpath{
    
    STActionSheet * actionSheet = [[STActionSheet alloc] initWithTitle:nil
                                                          buttonTitles:@[@"拍照",@"从手机相册选择",@"保存图片"] cancelTitle:@"取消"
                                                              delegate:self
                                   ];
    [actionSheet show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.pickerVC showTakePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 1) {
        [self.pickerVC showchosePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 2) {
        [PHPhotoLibrary saveImageToAssetsLibrary:self.iconButton.currentBackgroundImage
                                     libraryName:@"铺盖" successHandle:^{
                                         [SVProgressHUD showSuccessWithStatus:@"保存到相册成功"];
                                     } errorHandle:^(STSaveImageError error) {
                                         
                                     }];
    }
}
#pragma mark --Action Method
- (void)onSelectedLogoutButton{
    [self showAlertCancelAndConfirm:@"确定要退出登录吗?" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            //           [[STUserManger defult] removeUserPreferce];
            //            STNavigationController * nav = [[TMNavgationViewController alloc] initWithRootViewController:[BLLoginHomeViewController new]];
            //            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }
    }];
    
}
#pragma mark --NetWork Method
- (void)sendChangeNickNameRequest:(NSString*)nickName withModel:(STTableEasyModel*)model{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/editUsernameAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (nickName.length) {
        [dic setObject:nickName forKey:@"username"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 model.detailString = nickName;
                                                 [self.tableView reloadData];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendIconChangeRequest:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/item_upload"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    NSData * data =  UIImageJPEGRepresentation(image, 0.5);
    NSString *dataStr = [data base64EncodedStringWithOptions:0];
    [dic setObject:dataStr forKey:@"img"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSString * dataStr =  responseObject[@"data"];
                                                 [self sendIconUrlChangedRequestWithFace:dataStr image:image];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendIconUrlChangedRequestWithFace:(NSString*)face image:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/editFaceAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (face.length) {
        [dic setObject:face forKey:@"face"];
    }
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 //NSString * dataStr =  responseObject[@"data"];
                                                 [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                                                 self.imageModel.originImage = image;
                                                 [self.pickerVC reloadData];
                                                 [SVProgressHUD showSuccessWithStatus:@"修改头像成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

- (void)sendMyInfoRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/MemberListAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.userModel = [GCUserModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
